import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'dart:ui' as ui;

import 'package:path_provider/path_provider.dart';

class DrawPage extends StatefulWidget {
  const DrawPage({super.key});
  @override
  State<DrawPage> createState() => _PaperState();
}

class _PaperState extends State<DrawPage> {
  final List<Line> _lines = []; // 线列表
  int _activeColorIndex = 0; // 颜色激活索引
  int _activeStrokewidthIndex = 0; // 线宽激活索引

  // 支持的颜色
  final List<Color> supportColors = [Colors.black, Colors.red, Colors.orange];

  // 支持的线宽
  final List<double> supportStrokewidth = [1, 2, 3];

  Paint paint = Paint();
  late Uint8List _imageBytes;
  void drawLine(Canvas canvas, Line line) {
    paint.color = line.color;
    paint.strokeWidth = line.strokewidth;
    canvas.drawPoints(PointMode.polygon, line.points, paint);
  }

  /// 保存图片到相册
  Future<void> saveImageToGallery() async {
    final recorder = PictureRecorder();
    final canvas = Canvas(recorder);
    final size = Size(400, 400);
    for (var i = 0; i < _lines.length; i++) {
      drawLine(canvas, _lines[i]);
    }

    final picture = recorder.endRecording();
    final image =
        await picture.toImage(size.width.toInt(), size.height.toInt());
    _imageBytes = (await image.toByteData(format: ui.ImageByteFormat.png))!
        .buffer
        .asUint8List();

    final tempDir = await getTemporaryDirectory();
    final tempImagePath = '${tempDir.path}/image.png';
    final file = File(tempImagePath);
    await file.writeAsBytes(_imageBytes);

    final result = await GallerySaver.saveImage(file.path);
    if (result != null) {
      if (context.mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Image saved to gallery!')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Failed to save image.')));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('手绘'),
        ),
        body: Stack(
          children: [
            GestureDetector(
              onPanStart: _onPanStart,
              onPanUpdate: _onPanUpdate,
              child: CustomPaint(
                painter: PaperPainter(lines: _lines),
                child: ConstrainedBox(constraints: BoxConstraints.expand()),
              ),
            ),
            Positioned(
              bottom: 50,
              right: 0,
              child: StrokewidthSelector(
                  activeIndex: _activeStrokewidthIndex,
                  color: Colors.black,
                  supportStrokewidths: supportStrokewidth,
                  onSelect: _onSelectStorkWidth),
            ),
            Positioned(
              bottom: 50,
              left: 16,
              child: ColorSeletor(
                  supportColors: supportColors,
                  activeIndex: _activeColorIndex,
                  onSelect: onSelectColor),
            ),
            Positioned(
              bottom: 150,
              left: 16,
              child: IconButton(
                icon: Icon(Icons.clear, color: Colors.black),
                onPressed: () {
                  setState(() {
                    _lines.clear();
                  });
                },
              ),
            ),
            Positioned(
              bottom: 150,
              right: 16,
              child: IconButton(
                icon: Icon(Icons.check, color: Colors.black),
                onPressed: () {
                  saveImageToGallery();
                },
              ),
            ),
          ],
        ));
  }

  // 线宽选择
  void _onSelectStorkWidth(int index) {
    print(index);
    if (index != _activeStrokewidthIndex) {
      setState(() {
        _activeStrokewidthIndex = index;
      });
    }
  }

  // 颜色选择
  void onSelectColor(int index) {
    if (index != _activeColorIndex) {
      setState(() {
        _activeColorIndex = index;
      });
    }
  }

  // 绘制开始
  void _onPanStart(DragStartDetails details) {
    _lines.add(Line(
        points: [details.localPosition],
        strokewidth: supportStrokewidth[_activeStrokewidthIndex],
        color: supportColors[_activeColorIndex]));
  }

  // 绘制更新
  void _onPanUpdate(DragUpdateDetails details) {
    _lines.last.points.add(details.localPosition);
    setState(() {});
  }

  // void _clear() {}
}

class PaperPainter extends CustomPainter {
  PaperPainter({
    required this.lines,
  }) {
    _paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;
  }

  late Paint _paint;
  final List<Line> lines;

  @override
  void paint(Canvas canvas, Size size) {
    for (var i = 0; i < lines.length; i++) {
      drawLine(canvas, lines[i]);
    }
  }

  void drawLine(Canvas canvas, Line line) {
    _paint.color = line.color;
    _paint.strokeWidth = line.strokewidth;
    canvas.drawPoints(PointMode.polygon, line.points, _paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}

class Line {
  List<Offset> points;
  Color color;
  double strokewidth;

  Line({required this.points, this.color = Colors.black, this.strokewidth = 1});
}

// 线宽选择器
class StrokewidthSelector extends StatelessWidget {
  const StrokewidthSelector(
      {super.key,
      required this.activeIndex,
      required this.color,
      required this.supportStrokewidths,
      required this.onSelect});

  final List<double> supportStrokewidths;
  final int activeIndex;
  final Color color;
  final ValueChanged<int> onSelect;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: List.generate(supportStrokewidths.length, _buildByIndex),
      ),
    );
  }

  Widget _buildByIndex(int index) {
    bool select = index == activeIndex;
    return GestureDetector(
      onTap: () => onSelect(index),
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 2),
        padding: EdgeInsets.fromLTRB(8, 0, 8, 0),
        width: 70,
        height: 18,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: select ? Border.all(color: Colors.blue) : null),
        child: Container(
          color: color,
          height: supportStrokewidths[index],
        ),
      ),
    );
  }
}

// 颜色选择器
class ColorSeletor extends StatelessWidget {
  const ColorSeletor(
      {super.key,
      required this.supportColors,
      required this.activeIndex,
      required this.onSelect});

  final List<Color> supportColors;
  final int activeIndex;
  final ValueChanged<int> onSelect;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 3),
      child: Row(
        children: List.generate(supportColors.length, _buildByIndex),
      ),
    );
  }

  Widget _buildByIndex(int index) {
    bool select = index == activeIndex;
    return GestureDetector(
      onTap: () => onSelect(index),
      child: Container(
          alignment: Alignment.center,
          margin: EdgeInsets.symmetric(horizontal: 2),
          padding: EdgeInsets.all(2),
          width: 20,
          height: 20,
          decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: select ? Border.all(color: Colors.blue) : null),
          child: Container(
              decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: supportColors[index],
          ))),
    );
  }
}
